package com.h2cloud.aspect;

import com.h2cloud.depends.Response;
import com.h2cloud.aspect.Lock.Lock;
import com.h2cloud.aspect.Lock.myArgs;
import com.h2cloud.aspect.ThreadLockCache.ThreadLocalCacheable;
import com.h2cloud.aspect.cacheAble.Cacheable;
import com.h2cloud.aspect.cacheAble.CacheableEvict;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author: wulongkai
 * @create: 2022-08-27 01:24
 **/
@Service
public class WorkFlowBaseService {

    @Autowired
    private WorkFlowBizService workFlowBizService;

    @Autowired
    private WorkFlowBaseService selfProxy;

    public String testAdviceOrder(boolean throwEx) {
        try {
            if (throwEx) {
                throw new RuntimeException("出现错误");
            }
        } catch (Exception e) {

        }
        return "order-1";
    }

    public void excuteWorkFlow(boolean valid) {
        System.out.println("run start");
        Response<Boolean> response = workFlowBizService.agree(1, "longkai", valid);
        System.out.println("response = " + response);
        System.out.println("run end");
    }

    // 测试锁重入
    @Lock(cycle = 10, exceptionDesc = "请勿重复操作!!!", paramName = {"i", "a", "b"}, key = "getLock")
    public String getDataById(int i, int a, int b, int c) {
        System.err.println("getDataById进来了" + i);
//        this.callInnerFunction(i, a, b, c); // 直接调用，不走代理
        selfProxy.callInnerFunction(i, a, b, c);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "ok";
    }

    @Lock(cycle = 10, exceptionDesc = "请勿重复操作!!!", paramName = {"i", "a", "b"}, key = "getLock")
    public String callInnerFunction(int i, int a, int b, int c) {
        System.err.println("getDataByIdNner 进来了" + i);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "ok";
    }


    @Lock(cycle = 19, exceptionDesc = "请勿重复操作!!!", paramName = {"a", "b", "c.obj3.obj2.obj1.name"})
//    @Lock(cycle = 10, exceptionDesc = "请勿重复操作!!!", paramName = {"i", "a", "b", "c#ept#uid#age"}) // lockKey:com.h2cloud.test.WorkFlowBaseService.getDataByIdV2#1,0,2,teg,null,12
    public String getDataByIdV2(int i, int a, int b, myArgs c) {
        System.err.println("进来了" + i);
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "ok";
    }


    @ThreadLocalCacheable(paramName = "id")
    public String ThreadLocalCache(int id) {
        return "longkai-" + id;
    }

    String data = "cache1-";

    @Cacheable(key = "getRecord", expire = 10)
    public String getRecord(int id) {
        return this.data + id;
    }

    @CacheableEvict(key = "getRecord", paramName = {"id"})
    public void updateRecord(int id) {
        this.data = "cache2-";
    }
}
